package cn.nawang.ebeim.ui.service.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.nawang.ebeim.client.bean.BackStrategy;
import cn.nawang.ebeim.client.bean.ClientConfiguration;
import cn.nawang.ebeim.client.bean.StorageServer;
import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.ZookeeperUtil;
import cn.nawang.ebeim.client.version.DirectoryNode;
import cn.nawang.ebeim.client.version.FileNode;
import cn.nawang.ebeim.client.version.Node;
import cn.nawang.ebeim.client.version.VersionTree;
import cn.nawang.ebeim.client.version.VersionTreeUtil;
import cn.nawang.ebeim.ui.bean.DataSourceWrapper;
import cn.nawang.ebeim.ui.bean.Datasource;
import cn.nawang.ebeim.ui.bean.DatasourceConfig;
import cn.nawang.ebeim.ui.bean.DatasourceMenuBean;
import cn.nawang.ebeim.ui.bean.DatasourceTree;
import cn.nawang.ebeim.ui.bean.DatasourceView;
import cn.nawang.ebeim.ui.bean.FileElement;
import cn.nawang.ebeim.ui.bean.User;
import cn.nawang.ebeim.ui.service.DatasourceService;
import cn.nawang.ebeim.ui.util.ApiUtil;
import cn.nawang.ebeim.ui.util.FileOprt;
import cn.nawang.ebeim.ui.util.MACAddress;
import cn.nawang.ebeim.ui.util.UIversionTreeUtil;

/**
 * @ClassName: DatasourceServiceImpl
 * @Description: TODO
 * @author fanyb
 * @date Nov 11, 2015 3:44:41 PM
 * @version v1.0
 */
@Service("datasourceService")
public class DatasourceServiceImpl implements DatasourceService {

  @Autowired
  private HttpSession session;

  @Override
  public JSONObject getDeviceList(User user, JSONObject result) {
    String resultStr = ApiUtil.findBindDeviceNameByTerminalId(user.getId());
    JSONObject json = JSONObject.parseObject(resultStr);
    if (200 == (int) json.get("code")) {
      List<DatasourceMenuBean> list = (List<DatasourceMenuBean>) JSON
          .parseArray(json.get("list").toString(), DatasourceMenuBean.class);
      List<DatasourceTree> tree = new ArrayList<DatasourceTree>();
      DatasourceTree datasourceTree = null;
      for (int i = 0; i < list.size(); i++) {
        datasourceTree = new DatasourceTree();
        datasourceTree.setId(list.get(i).getTerminalId());
        datasourceTree.setPid("0");
        datasourceTree.setName(list.get(i).getBindDeviceName());
        datasourceTree.setType("0");
        datasourceTree.setFileType("设备");
        tree.add(datasourceTree);
      }
      result.put("code", 200);
      result.put("list", tree);
      result.put("message", "获取树成功！");
    }
    return result;
  }

  @Override
  public JSONObject getDatasourceListByTerminalId(String terminalId, User user, String dsType,JSONObject result) {
    String data = ApiUtil.getDataSourcesByCreateUserIdByPage(user.getId(), "0", "0", dsType, "", "",
        terminalId);
    JSONObject json = JSONObject.parseObject(data);
    if ("200".equals(json.get("code"))) {
      List<DatasourceView> list =
          (List<DatasourceView>) JSON.parseArray(json.get("list").toString(), DatasourceView.class);
      List<DatasourceTree> tree = new ArrayList<DatasourceTree>();
      DatasourceTree datasourceTree = null;
      for (int i = 0; i < list.size(); i++) {
        datasourceTree = new DatasourceTree();
        datasourceTree.setId(list.get(i).getId());
        datasourceTree.setPid(terminalId);
        datasourceTree.setName(list.get(i).getName());
        datasourceTree.setVersion(list.get(i).getCurrentVersionMajor() + ".0");
        datasourceTree.setType("1");
        datasourceTree.setDsId(list.get(i).getId());
        datasourceTree.setFileType("文件夹");
        datasourceTree.setRoot(list.get(i).getRoot());
        tree.add(datasourceTree);
      }
      result.put("code", 200);
      result.put("message","加载成功");
      result.put("list", tree);
    }
    return result;
  }

  @Override
  public JSONObject getDirectoryByfileJson(List<FileElement> fileJson, String id, String version,
      String dsId, String root,JSONObject result) {
    List<DatasourceTree> tree = new ArrayList<DatasourceTree>();
    DatasourceTree datasourceTree = null;
    for (int i = 0; i < fileJson.size(); i++) {
      datasourceTree = new DatasourceTree();
      datasourceTree.setId(fileJson.get(i).getPath() == "" ? "/" : fileJson.get(i).getPath());
      datasourceTree.setPid(id);
      datasourceTree.setName(fileJson.get(i).getName());
      datasourceTree.setType("2");
      datasourceTree.setVersion(version);
      datasourceTree.setPath(fileJson.get(i).getPath() == "" ? "/" : fileJson.get(i).getPath());
      datasourceTree.setDsId(dsId);
      datasourceTree.setFileType(fileJson.get(i).getType());
      datasourceTree.setRoot(root);
      if (!"文件".equals(fileJson.get(i).getType())) {
        tree.add(datasourceTree);
      }
    }
    result.put("code", 200);
    result.put("message", "加载成功");
    result.put("list", tree);
    return result;
  }

  /**
   * 获取文件目录列表
   */
  public List<FileElement> getDirectoryFiles(String dsId, String version, String path, User user)
      throws InterruptedException, UnsupportedEncodingException {
    path = java.net.URLDecoder.decode(path, "utf-8");
    ClientConfiguration.setCustomerId(user.getCustomerId());
    VersionTree tree = VersionTreeUtil.loadVersionTree(dsId, version);
    if (tree == null) {
      List<StorageServer> servers = CommonMethodsUtils.getServer();
      ClientConfiguration.setStorageServers(servers);
      tree = VersionTreeUtil.getVersionTree(dsId, version);
      ZookeeperUtil.close();
    }
    List<FileElement> list = new ArrayList<FileElement>();
    if (path == null || path.trim().isEmpty()) {
      path = "/";
    }
    if (tree == null) {
      return list;
    }
    if (!path.equals("/")) {
      Node node = tree.findNode(path);
      if (node == null) {} else if (node instanceof FileNode) {
        list.add(createFileElement(node));
      } else {
        DirectoryNode dn = (DirectoryNode) node;
        for (Node n : dn.getChildren().values()) {
          list.add(createFileElement(n));
        }
      }
    } else {
      Map<String, Node> map = tree.getRoot().getChildren();
      for (String key : map.keySet()) {
        Node node = map.get(key);
        if (node == null) {} else {
          list.add(createFileElement(node));
        }
      }
    }
    return list;
  }

  /**
   * @author zhangjf
   * @Description: 创建文件元素对象
   * @param @param node
   * @param @return
   * @return FileElement
   * @date 2015年10月29日上午8:41:52
   *
   * @修改人 zhangjf
   * @修改日期
   */
  public FileElement createFileElement(Node node) {
    FileElement fe = new FileElement(node.getName(), node.getPath());
    if (node instanceof FileNode) {
      fe.setType("文件");
      fe.setFileSize(((FileNode) node).getInfo().getFileSize());
      fe.setNid(((FileNode) node).getNid());
    } else {
      fe.setType("文件夹");
      fe.setNid(((DirectoryNode) node).getNid());
    }
    fe.setStatus(getStatus(node.getStatus()));
    return fe;
  }

  public String getStatus(byte status) {
    switch (status) {
      case Node.STATUS_ADD:
        return "新增";
      case Node.STATUS_BEFORE_DELETED:
      case Node.STATUS_DELETED:
        return "删除";
      case Node.STATUS_CHANGE:
        return "修改";
      case Node.STATUS_NOOP:
        return "新增";
      case 6:
        return "失败";
      default:
        return "没变化";
    }
  }

  @Override
  public JSONObject getDataSafeBox(JSONObject result) {
    // 判断数据库是否存在记录
    boolean exist = false;
    String version = null;
    String dsId = null;
    User user = (User) session.getAttribute("user");
    String data = ApiUtil.getDataSourcesByCreateUserIdAndDsType(user.getId(), "3");
    JSONObject dataJson = JSONObject.parseObject(data);
    JSONArray listJson = dataJson.getJSONArray("list");
    if (listJson.size() > 0) {
      exist = true;
      JSONObject dsJson = listJson.getJSONObject(0);
      version =
          dsJson.getString("currentVersionMajor") + "." + dsJson.getString("currentVersionMinor");
      dsId = dsJson.getString("id");
    } else {
      exist = false;
      // 默认新增一个数据源保险箱
      JSONObject addDs = addSafeboxTree();
      if (addDs.getString("code").equals("200")) {
        version = addDs.getString("version");
        dsId = addDs.getString("dsId");
      }
    }

    VersionTree tree = UIversionTreeUtil.getVersionTree(dsId, version);
    if (tree == null && !exist) {
      tree = new VersionTree();
      tree.getRoot().setNid(UUID.randomUUID().toString());
      tree.getRoot().setName("数据保险箱");
      VersionTreeUtil.save(tree, dsId, version);
      UIversionTreeUtil.uploadVersionTree(dsId, version);
    }
    return getTreeJson(tree, dsId, version, result);
  }

  public JSONObject getTreeJson(VersionTree versionTree, String dsId, String version,
      JSONObject result) {
    List<DatasourceTree> tree = new ArrayList<DatasourceTree>();
    DatasourceTree datasourceTree = null;
    datasourceTree = new DatasourceTree();
    datasourceTree.setId(versionTree.getRoot().getNid());
    datasourceTree.setPid("0");
    datasourceTree.setName(versionTree.getRoot().getName());
    datasourceTree.setType("0");
    datasourceTree.setVersion(version);
    datasourceTree.setPath("/");
    datasourceTree.setDsId(dsId);
    datasourceTree.setFileType(versionTree.getRoot().getName());
    datasourceTree.setRequestType("0");
    tree.add(datasourceTree);
    result.put("code", 200);
    result.put("message", "加载成功");
    result.put("list", tree);
    return result;
  }

  /**
   * @author zhangjf
   * @Description: 新增保险箱根树
   * @param @return
   * @return JSONObject
   * @date 2015年11月23日下午5:52:59
   *
   * @修改人 zhangjf
   * @修改日期
   */
  public JSONObject addSafeboxTree() {
    User user = (User) session.getAttribute("user");
    DataSourceWrapper dsWrapper = new DataSourceWrapper();
    Datasource ds = new Datasource();
    ds.setName("");
    ds.setIsOpenLocalBackup(0);
    ds.setCurrentVersionMajor(1);
    ds.setCurrentVersionMinor(0);
    ds.setDsSecurityRank(0);
    ds.setCount(0);
    ds.setDsType(Constants.DS_TYPE_TREE);
    ds.setTerminalId(MACAddress.getMACAddr());
    ds.setSpaceUsage(0L);
    String bindDeviceName = FileOprt
        .readFile(ClientConfiguration.getWorkingPath() + File.separator + user.getUsername());
    if (bindDeviceName != null && bindDeviceName.length() > 0) {
      ds.setBindDeviceName(bindDeviceName);
    } else {
      ds.setBindDeviceName(MACAddress.getComputerName());
    }

    DatasourceConfig dsCfg = new DatasourceConfig();
    dsCfg.setRoot("");

    BackStrategy bs = new BackStrategy();

    dsWrapper.setDatasource(ds);
    dsWrapper.setDatasourceConfig(dsCfg);
    dsWrapper.setBackStrategy(bs);
    dsWrapper.setUser(user);

    String data = ApiUtil.addDataSource(dsWrapper);
    JSONObject json = JSONObject.parseObject(data);
    JSONObject rs = new JSONObject();
    if (json.getString("code").equals("200")) {
      rs.put("code", "200");
      rs.put("version", "1.0");
      rs.put("dsId", json.getString("dsId"));
      return rs;
    } else {
      rs.put("code", "500");
      return rs;
    }
  }
}
